﻿using System;
using System.Globalization;
using System.Windows.Forms;
using Data.Model;
using DataAccess.SystemManage;
using Ninject;
using WinForm.Helper;

namespace WinForm.Dialog
{
    public partial class EditUserRole : Form
    {
        private static readonly IKernel Kernel = new StandardKernel(new DbModule());
        private readonly ISysUser _sysUser = Kernel.Get<ISysUser>();

        public EditUserRole()
        {
            InitializeComponent();
        }

        public EditUserRole(int id)
        {
            InitializeComponent();

            if (id > 0)
            {

                var db = new SysUser();
                var user = db.GetUser(id);
                lbUserid.Text = id.ToString(CultureInfo.InvariantCulture);
                textBoxX1.Text = user.Obj.username;


                RefreshListBox(id);

            }
        }

        private void RefreshListBox(int id)
        {
            var db = new SysUser();
            var selectedRoles = db.GetUserRoles(1, int.MaxValue, id);
            var unselectedRoles = db.GetUserUnRoles(id, 1, int.MaxValue);

            lbSelectedRole.DataSource = selectedRoles.Obj.Records;
            lbSelectedRole.DisplayMember = "RoleName";
            lbSelectedRole.ValueMember = "Roleid";
            lbUnseletedRole.DataSource = unselectedRoles.Obj.Records;
            lbUnseletedRole.DisplayMember = "RoleName";
            lbUnseletedRole.ValueMember = "Roleid";

        }

        private void btnAddUserRole_Click(object sender, EventArgs e)
        {
            var item = lbUnseletedRole.SelectedItem;
            if (item != null)
            {
                var role = (Role)item;
                var roleId = role.Roleid;
                var user = _sysUser.GetUser(Convert.ToInt32(lbUserid.Text));
                var username = string.Empty;
                if (user != null)
                {
                    username = user.Obj.username;
                }
                var userRole = new UserRole
                {
                    Roleid = roleId,
                    userid = Convert.ToInt32(lbUserid.Text),
                    rolename = role.Rolename,
                    username = username
                };
                _sysUser.CreateUpdateUserRole(userRole);
            }

            RefreshListBox(Convert.ToInt32(lbUserid.Text));

        }

        private void btnSubUserRole_Click(object sender, EventArgs e)
        {
            var item = lbSelectedRole.SelectedItem;
            if (item != null)
            {
                var role = (UserRole)item;
                var id = role.Id;

                _sysUser.DeleteUserRole(id);
            }

            RefreshListBox(Convert.ToInt32(lbUserid.Text));
        }



    }
}
